package com.lx.constant.segment.common;

import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.ArrayUtil;
import com.lx.constant.segment.Segment;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.query.Query;

import java.util.Collection;
import java.util.Objects;

/**
 * 自定义语句(完整的S/HQL),特殊处理该语句对象,不与其他语句组成混合
 *
 * @author lx
 * @create 2022/12/23 16:06
 **/
@Getter
@Setter
public class QlCompleteSegment extends Segment {

    /**
     * 是否为HQL语句
     */
    private Boolean isHQL;

    /**
     * 语句
     */
    private String qlString;

    /**
     * Hibernate参数设置列表
     */
    private Pair<String, ?>[] hibernateParams;

    @Override
    public void setHibernateParamByQuery(boolean isHQL, Query query) {
        Pair<String, ?>[] hibernateParams = this.hibernateParams;
        if (ArrayUtil.isEmpty(hibernateParams)) {
            return;
        }

        for (Pair<String, ?> hp : hibernateParams) {
            if (hp == null) {
                continue;
            }
            Object value = hp.getValue();
            if (value instanceof Object[]) {
                query.setParameterList(hp.getKey(), (Object[]) value);
            } else if (value instanceof Collection) {
                query.setParameterList(hp.getKey(), (Collection) value);
            } else {
                query.setParameter(hp.getKey(), value);
            }
        }
    }

    @Override
    public boolean needReplace(Segment t1) {
        if (t1 instanceof QlCompleteSegment) {
            QlCompleteSegment tt = (QlCompleteSegment) t1;
            return Objects.equals(this.isHQL, tt.getIsHQL());
        }
        return false;
    }
}
